package com.bq.gulimall.gateway.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;

/**
 * 解决跨域问题
 */
// @configuration + @Bean = 在 Spring 框架中的 <bean/> 标签
@Configuration    //标注它是一个配置类
//@EnableConfigurationProperties(CORSProperties.class)
public class GulimallCorsConfiguration{

    @Bean // 将它加入到容器中
    public CorsWebFilter corsWebFilter(CORSProperties corsProperties){
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
//        1、配置跨域
        // 允许哪些请求头进行跨域
        List<String> allowedHeaders = corsProperties.getAllowedHeaders();
        for (String allowedHeader : allowedHeaders) {
            corsConfiguration.addAllowedHeader(allowedHeader);
        }
        // 允许哪些请求方式进行跨域
        List<String> allowedMethods = corsProperties.getAllowedMethods();
        for (String allowedMethod : allowedMethods) {
            corsConfiguration.addAllowedMethod(allowedMethod);
        }
        // 允许哪些请求来源进行跨域
        List<String> allowedOrigins = corsProperties.getAllowedOrigins();
        for (String allowedOrigin : allowedOrigins) {
            corsConfiguration.addAllowedOrigin(allowedOrigin);
        }
        // 是否允许携带 cookie 跨域
        corsConfiguration.setAllowCredentials(corsProperties.getAllowCredentials());
        // 有效期
        corsConfiguration.setMaxAge(corsProperties.getMaxAge());
        urlBasedCorsConfigurationSource.registerCorsConfiguration(corsProperties.getFilterPath(),corsConfiguration);
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }
}